package com.elder.business.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.EgressRegisterRecordsVO;
import com.elder.business.domain.ElderlyInfo;
import com.elder.business.mapper.ElderlyApartmentBedsMapper;
import com.elder.business.mapper.ElderlyInfoMapper;
import com.elder.common.core.domain.AjaxResult;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.enums.ApplyStatus;
import com.elder.common.enums.BedType;
import com.elder.common.utils.DateUtils;
import com.elder.common.utils.LongUtils;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.bean.BeanUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.elder.business.mapper.EgressRegisterRecordsMapper;
import com.elder.business.domain.EgressRegisterRecords;
import com.elder.business.service.IEgressRegisterRecordsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 外出申请记录Service业务层处理
 * 
 * @author zyk
 * @date 2023-11-26
 */
@Service
public class EgressRegisterRecordsServiceImpl implements IEgressRegisterRecordsService 
{
    @Autowired
    private EgressRegisterRecordsMapper egressRegisterRecordsMapper;
    @Autowired
    private ElderlyInfoMapper elderlyInfoMapper;
    @Autowired
    private ElderlyApartmentBedsMapper elderlyApartmentBedsMapper;

    /**
     * 查询外出申请记录
     * 
     * @param id 外出申请记录主键
     * @return 外出申请记录
     */
    @Override
    public JSONObject selectEgressRegisterRecordsById(Long id)
    {
        EgressRegisterRecords registerRecords = egressRegisterRecordsMapper.selectEgressRegisterRecordsById(id);
        ElderlyInfo elderlyInfo = elderlyInfoMapper.selectElderlyInfoById(registerRecords.getElderId());
        JSONObject obj = new JSONObject();
        if(Objects.nonNull(registerRecords)){
            obj.put("id",StringNewUtils.long2Str(registerRecords.getId()));
            obj.put("elderId",StringNewUtils.long2Str(registerRecords.getElderId()));
            obj.put("elderName",elderlyInfo.getElderName());
            obj.put("apartmentId",StringNewUtils.long2Str(elderlyInfo.getApartmentId()));
            obj.put("apartmentName",elderlyInfo.getApartmentName());
            obj.put("bedCode",elderlyInfo.getBedCode());
            obj.put("awayTime",DateUtils.dateStrMIAO(registerRecords.getAwayTime()));
            obj.put("awayReson",registerRecords.getAwayReson());
            obj.put("expectedBackTime",DateUtils.dateStrMIAO(registerRecords.getExpectedBackTime()));
            obj.put("realityBackTime",DateUtils.dateStrMIAO(registerRecords.getRealityBackTime()));
            obj.put("escorted",registerRecords.getEscorted());
            obj.put("relation",registerRecords.getRelation());
            obj.put("applyTime",DateUtils.dateStrMIAO(registerRecords.getApplyTime()));
            obj.put("applicant",registerRecords.getApplicant());
            obj.put("applyStatus",ApplyStatus.getCnName(registerRecords.getApplyStatus()));
            obj.put("escortedPhone",registerRecords.getEscortedPhone());
            obj.put("auditTime",DateUtils.dateStrMIAO(registerRecords.getAuditTime()));
            obj.put("auditPerson",registerRecords.getAuditPerson());
        }
        return obj;
    }

    /**
     * 查询外出申请记录列表
     * 
     * @param egressRegisterRecords 外出申请记录
     * @return 外出申请记录
     */
    @Override
    public List<EgressRegisterRecords> selectEgressRegisterRecordsList(EgressRegisterRecords egressRegisterRecords)
    {
        return egressRegisterRecordsMapper.selectEgressRegisterRecordsList(egressRegisterRecords);
    }

    /**
     * 新增外出申请记录
     * 
     * @param egressvo 外出申请记录
     * @return 结果
     */
    @Override
    public int insertEgressRegisterRecords(EgressRegisterRecordsVO egressvo)
    {
        EgressRegisterRecords egressRecords = new EgressRegisterRecords();
        BeanUtils.copyProperties(egressvo,egressRecords);
        egressRecords.setId(SnowGenerator.getId());
        egressRecords.setElderId(LongUtils.str2Long(egressvo.getElderId()));
        egressRecords.setAwayTime(DateUtils.getDateSeconds(egressvo.getAwayTime()));
        if(!StringNewUtils.isEmpty(egressvo.getExpectedBackTime())){
            egressRecords.setExpectedBackTime(DateUtils.getDateSeconds(egressvo.getExpectedBackTime()));
        }
        if(!StringNewUtils.isEmpty(egressvo.getRealityBackTime())){
            egressRecords.setRealityBackTime(DateUtils.getDateSeconds(egressvo.getRealityBackTime()));
        }
        egressRecords.setApplyStatus(ApplyStatus.APPLUING.getValue());
        egressRecords.setApplyTime(DateUtils.getLongTime());
        egressRecords.setCreateTime(DateUtils.getLongTime());
        egressRegisterRecordsMapper.insertEgressRegisterRecords(egressRecords);
        return 1;
    }

    /**
     * 修改外出申请记录
     * 
     * @param egressvo 外出申请记录
     * @return 结果
     */
    @Override
    public int updateEgressRegisterRecords(EgressRegisterRecordsVO egressvo)
    {
        EgressRegisterRecords egress = new EgressRegisterRecords();
        BeanUtils.copyProperties(egressvo,egress);
        egress.setId(LongUtils.str2Long(egressvo.getId()));
        if(!StringNewUtils.isEmpty(egressvo.getAwayTime())){
            egress.setAwayTime(DateUtils.getDateSeconds(egressvo.getAwayTime()));
        }
        if(!StringNewUtils.isEmpty(egressvo.getExpectedBackTime())){
            egress.setExpectedBackTime(DateUtils.getDateSeconds(egressvo.getExpectedBackTime()));
        }
        if(!StringNewUtils.isEmpty(egressvo.getRealityBackTime())){
            egress.setRealityBackTime(DateUtils.getDateSeconds(egressvo.getRealityBackTime()));
        }
        egress.setUpdateTime(DateUtils.getLongTime());
        return egressRegisterRecordsMapper.updateEgressRegisterRecords(egress);
    }

    /**
     * 批量删除外出申请记录
     * 
     * @param ids 需要删除的外出申请记录主键
     * @return 结果
     */
    @Override
    public int deleteEgressRegisterRecordsByIds(Long[] ids)
    {
        return egressRegisterRecordsMapper.deleteEgressRegisterRecordsByIds(ids);
    }

    /**
     * 删除外出申请记录信息
     * 
     * @param id 外出申请记录主键
     * @return 结果
     */
    @Override
    public int deleteEgressRegisterRecordsById(Long id)
    {
        return egressRegisterRecordsMapper.deleteEgressRegisterRecordsById(id);
    }

    /***
     * @description 获取外出记录
     * @param pageNum
     * @param pageSize
     * @return TableDataInfo
     * @author zyk
     * @date 2023/12/11 19:45
     */
    @Override
    public TableDataInfo getEgressRegisterRecords(String elderName, String startTime,String endTime, String applyStatus, Integer pageNum, Integer pageSize) {

        List<Long> elderIds = null;
        if(!StringNewUtils.isEmpty(elderName)){
            List<ElderlyInfo> elderinfoList = elderlyInfoMapper.getElderinfoList(elderName);
            elderIds = elderinfoList.stream().map(ElderlyInfo::getElderId).collect(Collectors.toList());
        }
        Long startDayTime = null;
        Long endDayTime = null;
        if(!StringNewUtils.isEmpty(startTime) && !StringNewUtils.isEmpty(endTime)){
            Long dateStart = DateUtils.getTargetDateSeconds(startTime);
            Long dateEnd = DateUtils.getTargetDateSeconds(endTime);
            startDayTime = DateUtils.getDayStartTime(dateStart);
            endDayTime = DateUtils.getDayEndTime(dateEnd);
        }
        //获取分页数据
        PageHelper.startPage(pageNum,pageSize);
        List<EgressRegisterRecords> list = egressRegisterRecordsMapper.getEgressRegisterRecordsList(elderIds,ApplyStatus.getValue(applyStatus) ,startDayTime,endDayTime);
        PageInfo<EgressRegisterRecords> page = new PageInfo<>(list);
        List<EgressRegisterRecords> recordsList = page.getList();

        Map<Long, String> elderMap = elderlyInfoMapper.getAllElderList()
                .stream().collect(Collectors.toMap(ElderlyInfo::getElderId, ElderlyInfo::getElderName));
        List<JSONObject> egressRecordList = recordsList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("id", StringNewUtils.long2Str(v.getId()));
            obj.put("elderId", StringNewUtils.long2Str(v.getElderId()));
            obj.put("elderName",elderMap.get(v.getElderId()));
            obj.put("awayTime", DateUtils.dateStrMIAO(v.getAwayTime()));
            obj.put("awayReson", v.getAwayReson());
            obj.put("expectedBackTime", DateUtils.dateStrMIAO(v.getExpectedBackTime()));
            obj.put("realityBackTime", DateUtils.dateStrMIAO(v.getRealityBackTime()));
            obj.put("escorted", v.getEscorted());
            obj.put("relation", v.getRelation());
            obj.put("applyTime", DateUtils.dateStrMIAO(v.getApplyTime()));
            obj.put("applicant", v.getApplicant());
            obj.put("applyStatus", ApplyStatus.getCnName(v.getApplyStatus()));
            obj.put("escortedPhone", v.getEscortedPhone());
            obj.put("auditTime", DateUtils.dateStrMIAO(v.getAuditTime()));
            obj.put("auditPerson", v.getAuditPerson());
            return obj;
        }).collect(Collectors.toList());
        TableDataInfo result = new TableDataInfo();
        result.setCode(200);
        result.setMsg("success");
        result.setTotal(page.getTotal());
        result.setRows(egressRecordList);
        return result;
    }

    /***
     * @description 审批外出申请
     * @param elderId
     * @param applyStatus
     * @return AjaxResult
     * @author zyk
     * @date 2023/12/11 20:10
     */
    @Override
    @Transactional
    public AjaxResult updateEgressRegisterApprove(Long elderId, String applyStatus,String notes) {
        //修改审批状态
        Long auitTime = DateUtils.getLongTime();
        egressRegisterRecordsMapper.updateEgressRegisterApplyStatus(elderId,ApplyStatus.getValue(applyStatus),auitTime,notes);
        if(Objects.equals(applyStatus,ApplyStatus.APPLY_PASS.getDisplayName())){
            //修改床位居住状态
            elderlyApartmentBedsMapper.updateBedLiveStatus(elderId,303);
        }
        return AjaxResult.success();
    }
}
